package com.paypalpay.util;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.UUID;


public class SignUtil {
	/** 加密算法 */
	private static final String algorithm = "HmacSHA1";
	private static final String key = "@ABCDEFGHIJKLMNO";// @ABCDEFGHIJKLMNO

	/***
	 * 产生数字签名
	 * 
	 * @param data
	 * @return
	 */
	public static String generateSign(String data) {
		try {
			SecretKeySpec sk = new SecretKeySpec(key.getBytes("utf-8"), algorithm);
			Mac mac = Mac.getInstance(algorithm);
			mac.init(sk);
			byte[] res = mac.doFinal(data.getBytes("UTF-8"));
			return Base64.encode(res);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public static String generateSign(String data, String secretKey) {
		try {
			SecretKeySpec sk = new SecretKeySpec(secretKey.getBytes("UTF-8"), algorithm);
			Mac mac = Mac.getInstance(algorithm);
			mac.init(sk);
			byte[] res = mac.doFinal(data.getBytes("UTF-8"));
			return Base64.encode(res);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public static boolean checkSign(String data, String sign) {
		if (data == null || "".equals(data) || sign == null || "".equals(sign)) {
			return false;
		}
		return sign.equals(generateSign(data));
	}

	public static void main(String[] args) {		
		System.out.println(generateSign("<head><access_code>P000512</access_code><cmd_type>orderPackage</cmd_type><timestamp>1541571454106</timestamp><version>1.0</version></head><body><device_id>866819000068656</device_id><device_type>5</device_type><is_open>1</is_open><order_period>1</order_period><package_code>DP20180903000086</package_code><package_name>自测4G流量套餐</package_name><pay_amount >1</pay_amount ></body>","mlfcVrCbIQe06lEA1g4Fu6Ikfcf4jlMp"));
	}
	
	public static String randomStr(){
	
		try {
			String ran = UUID.randomUUID().toString();
			
			//确定计算方法
			MessageDigest md5=MessageDigest.getInstance("MD5");
			BASE64Encoder base64en = new BASE64Encoder();
			
			String newstr=base64en.encode(md5.digest(ran.getBytes("utf-8")));
			return newstr;
		 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		return null;
	}
	

}
